package com.atguigu.tingshu.account.listener;

import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.RabbitConstant;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class AccountMqListener {
    @Autowired
    private UserAccountService userAccountService;


    //消费者监听消息，初始化账户
    @RabbitListener(
            bindings = {
                    @QueueBinding(
                            exchange = @Exchange(value = RabbitConstant.USER_EXCHANGE, type = ExchangeTypes.TOPIC),
                            value = @Queue(value = RabbitConstant.USER_REGISTER_QUEUE, durable = "true"),
                            key = RabbitConstant.USER_REGISTER_RK
                    )
            }
    )
    public void initAccount(Channel channel, Message message, Long userId) throws IOException {
        try {
            userAccountService.saveAccount(userId);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            log.info("{} 执行成功, userId:{}" , "登录初始化账户信息" , userId);
        } catch (IOException e) {
            //第一次异常 尝试重试 消费
            if(message.getMessageProperties().isRedelivered()){
                //消息多次消费异常:打印日志 并丢弃消息
                log.error("{} 执行失败, userId:{}" , "登录初始化账户信息" , userId);
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            }else {
                //消息第一次消费异常:打印日志 并重新入队
                log.error("{} 执行失败, userId:{}" , "登录初始化账户信息" , userId);
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            }

        }

    }
}

